package com.mxin.network

import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import java.util.concurrent.TimeUnit

/**
 *  Created by ：2020/7/28
 *  author : Administrator
 *
 */
class OkHttpFactory {

    companion object{

        private const val CONNECT_TIMEOUT = 6L //配置连接超时时间

        private const val READ_TIMEOUT = 10L //配置读取超时时间

        private const val WRIT_TIMEOUT = 10L //配置写超时时间

        private var interceptorList : MutableList<Interceptor>?=null

        internal fun setInterceptor(vararg interceptors : Interceptor){
            if(interceptorList==null){
                interceptorList = mutableListOf(*interceptors)
            }else{
                interceptorList?.addAll(interceptors)
            }
        }

        internal val httpClient by lazy {
            val builder = OkHttpClient.Builder()
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIMEOUT,TimeUnit.SECONDS)
                .writeTimeout(WRIT_TIMEOUT,TimeUnit.SECONDS)
                .addInterceptor(HttpLoggingInterceptor().also { it.level = if(ServiceGeneral.debug) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE })
            if(!interceptorList.isNullOrEmpty()){
                interceptorList!!.forEach {
                    builder.addInterceptor(it)
                }
            }
            builder
        }

        @JvmStatic
        val httpClientSimple by lazy {
            val builder = OkHttpClient.Builder()
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIMEOUT,TimeUnit.SECONDS)
                .writeTimeout(WRIT_TIMEOUT,TimeUnit.SECONDS)
            builder
        }

        @JvmStatic
        fun createHttpClient(block:(OkHttpClient.Builder)->Unit):OkHttpClient.Builder{
            val builder = OkHttpClient.Builder()
                    .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                    .readTimeout(READ_TIMEOUT,TimeUnit.SECONDS)
                    .writeTimeout(WRIT_TIMEOUT,TimeUnit.SECONDS)
            block(builder)
            return builder
        }

    }


}